package com.yeskery.nut.application.tomcat;

import com.yeskery.nut.application.JksSecureServerContext;
import com.yeskery.nut.application.SecureServerContext;
import com.yeskery.nut.core.NutException;
import org.apache.catalina.connector.Connector;
import org.apache.coyote.ProtocolHandler;
import org.apache.coyote.http11.AbstractHttp11JsseProtocol;

/**
 * 基于Tomcat的HttpServer实现HTTPS服务
 * @author sprout
 * @version 1.0
 * 2022-08-05 18:46
 */
public class TomcatSecureNutServer extends TomcatNutServer {

    /** SecureServerContext对象 */
    private final SecureServerContext secureServerContext;

    /**
     * 构建基于Tomcat的HttpServer实现HTTPS服务
     * @param secureServerContext SecureServerContext对象
     */
    public TomcatSecureNutServer(SecureServerContext secureServerContext) {
        this.secure = true;
        if (!(secureServerContext instanceof JksSecureServerContext)) {
            throw new NutException("Tomcat Secure Only Support JksSecureServerContext");
        }
        this.secureServerContext = secureServerContext;
    }

    @Override
    protected Connector buildServerConnector(int port) {
        Connector connector = super.buildServerConnector(port);
        ProtocolHandler handler = connector.getProtocolHandler();
        if (!(handler instanceof AbstractHttp11JsseProtocol)) {
            throw new NutException("SSL Connector Protocol Handler Must Be an AbstractHttp11JsseProtocol Instance.");
        }
        JksSecureServerContext jksSecureServerContext = (JksSecureServerContext) secureServerContext;
        AbstractHttp11JsseProtocol<?> protocol = (AbstractHttp11JsseProtocol<?>) handler;
        protocol.setSSLEnabled(true);
        protocol.setSslProtocol(SecureServerContext.TLS_V1_2);
        protocol.setKeystoreFile(jksSecureServerContext.getJksPath());
        protocol.setKeystorePass(jksSecureServerContext.getJksPassword());
        protocol.setKeystoreType("JKS");

        connector.setScheme("https");
        connector.setSecure(true);
        return connector;
    }
}
